#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import glob

TIME_HEADER="["

def update_time(line):
    timehead = line.split(']')[0]
    return timehead.split()[-1]

def get_beacon(line, timestr):
    # <02><03><len><st1><st2><data1><data2><crc1><crc2>
    # 0  3          13        21     25         31
    if line.startswith('<') and len(line)>=36 and line[3:5]=='><' and line[31:33]=='><':
        id = int(line[1:3], 16)
        if id > 5:
            return 0, []
        st = line[13:19]
        data1str = line[21:23]
        data2str = line[25:27]
        data1 = int(data1str, 16)
        data2 = int(data2str, 16)
        data = data1*256+data2
        ret = []
        for i in range(10):
            if (data & (1<<i)):
                ret.append(str((id-1)*10+i+1))
        #print("%s   %s  %s  %s%s    %s"%(timestr, id, st, data1str, data2str, '    '.join(ret)))
        #print("%s   %s  %s%s    %s"%(timestr, id, data1str, data2str, '    '.join(ret)))
        print("%s:%s%s,"%(id, data1str, data2str), end='')
        return id, ret
    return 0, []

def parse_file(filename):
    with open(filename) as f:
        timestr = ""
        cid = 1
        group = []
        for l in f:
            if l.startswith('[') and l[1].isupper():
                timestr = update_time(l)
            nid, tlist = get_beacon(l, timestr)
            if nid != 0:
                if nid < cid:
                    print('\nRET\t', end='')
                    if len(group) == 0:
                        group.append('0')
                    print('%s\t%s\t0\t0\t'%(timestr, '\t'.join(group)), end='')
                    group = tlist
                else:
                    group.extend(tlist)
                cid = nid

def usage():
    print('===bparser用于解析cbtc_ats的日志，获取信标的记录===')
    print('bparser -d            将解析当前目录下所有以cbtc_ats为前缀的日志')
    print('bparser <file1 ...>   将解析指定的日志')

if __name__ == '__main__':
    if len(sys.argv) == 1:
        usage()
    if len(sys.argv) > 1:
        if sys.argv[1] == '-d':
            for f in glob.glob('cbtc_ats_*'):
                parse_file(f)
        else:
            for filename in sys.argv[1:]:
                parse_file(filename)
